package com.cn.shuangzi.userinfo.activity;

import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.cn.shuangzi.R;
import com.cn.shuangzi.SZApp;
import com.cn.shuangzi.SZBaseActivity;
import com.cn.shuangzi.SZBaseWebActivity;
import com.cn.shuangzi.SZManager;
import com.cn.shuangzi.bean.VipInfo;
import com.cn.shuangzi.bean.VipPriceInfo;
import com.cn.shuangzi.common.SZConst;
import com.cn.shuangzi.loginplugin.common.socialized.ShareWeChat;
import com.cn.shuangzi.loginplugin.common.socialized.pay.PayManager;
import com.cn.shuangzi.loginplugin.common.socialized.pay.PayType;
import com.cn.shuangzi.retrofit.SZCommonResponseListener;
import com.cn.shuangzi.retrofit.SZRetrofitManager;
import com.cn.shuangzi.userinfo.adp.VipNewAdp;
import com.cn.shuangzi.userinfo.adp.VipPowerAdp;
import com.cn.shuangzi.userinfo.bean.VipPowerInfo;
import com.cn.shuangzi.userinfo.common.UserManager;
import com.cn.shuangzi.util.SZDateUtil;
import com.cn.shuangzi.util.SZIRecyclerViewUtil;
import com.cn.shuangzi.util.SZImageLoader;
import com.cn.shuangzi.util.SZToast;
import com.cn.shuangzi.util.SZUtil;
import com.cn.shuangzi.util.SZValidatorUtil;
import com.cn.shuangzi.util.SZXmlUtil;
import com.cn.shuangzi.view.AlertWidget;
import com.cn.shuangzi.view.shape_imgview.CustomShapeImageView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import io.reactivex.Observable;

/**
 * Created by CN.
 */

public abstract class SZBuyVipNewActivity extends SZBaseActivity implements View.OnClickListener {
    private ImageView imgBackSub;
    private TextView txtGetInvoice;
    private LinearLayout lltUnLogin;
    private LinearLayout lltUser;
    private CustomShapeImageView imgAvatar;
    private TextView txtNickname;
    private ImageView imgVip;
    private TextView txtNormalUser;
    private LinearLayout lltVipDate;
    private TextView txtVipDate;
    private RecyclerView recyclerViewVip;
    private RelativeLayout rltAlipay;
    private ImageView chkAliPay;
    private RelativeLayout rltWechatPay;
    private ImageView chkWechatPay;
    private Button btnPay;
    private LinearLayout lltProtocol;
    private TextView txtVipSkuNotes;
    private CheckBox chkBoxAgree;
    private TextView txtVipProtocol;
    private LinearLayout lltContinuePay;
    private TextView txtVipContinueProtocol;
    private TextView txtVipPowerDesc;
    private RecyclerView recyclerViewVipPower;


    public SZImageLoader imageLoader;
    public List<VipPriceInfo> vipPriceInfoList;
    private List<VipPriceInfo> vipRetentionPriceInfoList;
    public List<VipPowerInfo> vipPowerInfoList;
    public VipPriceInfo vipPriceInfoCheck;

    public String payType;

    private SZXmlUtil xmlUtilVipBought;
    public boolean isCancelPay = false;

    //设置已购买会员次数
    private void setBoughtVip(VipPriceInfo vipPriceInfo) {
        if (xmlUtilVipBought == null) {
            xmlUtilVipBought = new SZXmlUtil(SZConst.VIP_BOUGHT);
        }
        String key = getUserId() + "_" + vipPriceInfo.getFpId();
        xmlUtilVipBought.put(key, xmlUtilVipBought.getInt(key) + 1);
    }

    //设置已购买会员次数
    private boolean isBoughtVip(VipPriceInfo vipPriceInfo) {
        if (xmlUtilVipBought == null) {
            xmlUtilVipBought = new SZXmlUtil(SZConst.VIP_BOUGHT);
        }
        String key = getUserId() + "_" + vipPriceInfo.getFpId();
        int times = xmlUtilVipBought.getInt(key);
        return times > 0;
    }

    @Override
    protected int onGetChildView() {
        return R.layout.activity_buy_vip_new;
    }

    @Override
    protected void onBindChildViews() {
        imgBackSub = findViewById(R.id.imgBackSub);
        txtGetInvoice = findViewById(R.id.txtGetInvoice);
        lltUnLogin = findViewById(R.id.lltUnLogin);
        lltUser = findViewById(R.id.lltUser);
        imgAvatar = findViewById(R.id.imgAvatar);
        txtNickname = findViewById(R.id.txtNickname);
        imgVip = findViewById(R.id.imgVip);
        txtNormalUser = findViewById(R.id.txtNormalUser);
        lltVipDate = findViewById(R.id.lltVipDate);
        txtVipDate = findViewById(R.id.txtVipDate);
        recyclerViewVip = findViewById(R.id.recyclerViewVip);
        rltAlipay = findViewById(R.id.rltAlipay);
        chkAliPay = findViewById(R.id.chkAliPay);
        rltWechatPay = findViewById(R.id.rltWechatPay);
        chkWechatPay = findViewById(R.id.chkWechatPay);
        btnPay = findViewById(R.id.btnPay);
        lltProtocol = findViewById(R.id.lltProtocol);
        chkBoxAgree = findViewById(R.id.chkBoxAgree);
        txtVipProtocol = findViewById(R.id.txtVipProtocol);
        lltContinuePay = findViewById(R.id.lltContinuePay);
        txtVipContinueProtocol = findViewById(R.id.txtVipContinueProtocol);
        txtVipSkuNotes = findViewById(R.id.txtVipSkuNotes);
        txtVipPowerDesc = findViewById(R.id.txtVipPowerDesc);
        recyclerViewVipPower = findViewById(R.id.recyclerViewVipPower);
    }

    @Override
    protected void onBindChildListeners() {
    }

    @Override
    protected void onChildViewCreated() {
        setStatusBarColor(R.color.bgVipColor);
        setStatusBarTextColorStyleBelowBar(false);
        getBaseView().setBackgroundColor(getResources().getColor(R.color.bgVipColor));
        txtGetInvoice.setVisibility(isShowGetInvoice() ? View.VISIBLE : View.GONE);
        txtVipPowerDesc.setVisibility(isShowVipPowerDesc() ? View.VISIBLE : View.GONE);
        isShowContent(false);
        imageLoader = new SZImageLoader(this);
        setUserInfoView();
        SZIRecyclerViewUtil.setHorizontalLinearLayoutManager(this, recyclerViewVip, android.R.color.transparent, SZUtil.dip2px(8), true, false);
        SZIRecyclerViewUtil.setGridLinearLayoutManager(this, recyclerViewVipPower, getVipRecyclerViewSpanCount() == 0 ? 3 : getVipRecyclerViewSpanCount(), android.R.color.transparent, 0, false, false);
        onReloadData(false);

        SZManager.getInstance().onUMEvent(SZConst.EVENT_BUY_VIP_PAGE_SHOW);
    }

    private void setUserInfoView() {
        if (isLogin(false)) {
            findViewById(R.id.lltUser).setVisibility(View.VISIBLE);
            findViewById(R.id.lltUnLogin).setVisibility(View.GONE);
            imageLoader.load(imgAvatar, getAvatar());
            txtNickname.setText(getNickname());
        } else {
            findViewById(R.id.lltUser).setVisibility(View.GONE);
            findViewById(R.id.lltUnLogin).setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (isPrepared()) {
            setUserInfoView();
        }
    }

    @Override
    protected void onReloadData(boolean isRefresh) {
        showBarTransparentStyle();
        if (isLogin(false)) {
            requestVipUserInfo(getVipUserObservable());
        } else {
            getVipPrice();
        }
    }

    private void setPayTypeCheck() {
        if (payType != null) {
            switch (payType) {
                case SZConst.WXPAY:
                    chkAliPay.setImageResource(R.mipmap.vip_icon_box_off);
                    chkWechatPay.setImageResource(R.mipmap.vip_icon_box_on);
                    break;
                case SZConst.ALIPAY:
                    chkAliPay.setImageResource(R.mipmap.vip_icon_box_on);
                    chkWechatPay.setImageResource(R.mipmap.vip_icon_box_off);
                    break;
            }
        }
    }

    private void getVipPrice() {
        request(SZRetrofitManager.getInstance().getSZRequest().getVipPriceV3(), new SZCommonResponseListener() {
            @Override
            public void onResponseSuccess(String data) {
                isShowContent(true);
                List<VipPriceInfo> vipPriceInfoListTemp = new Gson().fromJson(data, new TypeToken<List<VipPriceInfo>>() {
                }.getType());
                vipPriceInfoList = new ArrayList<>();
                vipRetentionPriceInfoList = new ArrayList<>();
                for (VipPriceInfo vipPriceInfo : vipPriceInfoListTemp) {
                    if (vipPriceInfo.isRetention()) {
                        vipRetentionPriceInfoList.add(vipPriceInfo);
                    } else {
                        vipPriceInfoList.add(vipPriceInfo);
                    }
                }
                vipPriceInfoList.get(0).setCheck(true);
                vipPriceInfoCheck = vipPriceInfoList.get(0);
                final VipNewAdp vipNewAdp = new VipNewAdp(getActivity(), vipPriceInfoList);
                vipNewAdp.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        for (VipPriceInfo vipPriceInfo : vipPriceInfoList) {
                            vipPriceInfo.setCheck(false);
                        }
                        vipPriceInfoCheck = vipPriceInfoList.get(position);
                        vipPriceInfoList.get(position).setCheck(true);
                        vipNewAdp.notifyDataSetChanged();
                        showPayType();
                        SZManager.getInstance().onUMEvent(SZConst.EVENT_CLICK_VIP_SKU, vipPriceInfoCheck.getFpName());
                    }
                });
                recyclerViewVip.setAdapter(vipNewAdp);
                vipPowerInfoList = getVipPowerInfoList();
                VipPowerAdp vipPowerAdp = new VipPowerAdp(getActivity(), vipPowerInfoList);
                vipPowerAdp.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                        VipPowerInfo vipPowerInfo = vipPowerInfoList.get(position);
                        if (!onVipPowerItemClick(position, vipPowerInfo)) {
                            showNormalAlert(vipPowerInfo.getPowerName(), vipPowerInfo.getPowerDesc(), null);
                        }
                    }
                });
                recyclerViewVipPower.setAdapter(vipPowerAdp);
                showPayType();
            }

            @Override
            public void onResponseError(int errorCode, String errorMsg) {
                showErrorWithMsg(errorCode, errorMsg);
            }
        });
    }

    private void showPayType() {
        payType = null;
        if (vipPriceInfoCheck != null) {
            if (vipPriceInfoCheck.hasWechatPay()) {
                payType = SZConst.WXPAY;
                setPayTypeCheck();
                rltWechatPay.setVisibility(View.VISIBLE);
            } else {
                rltWechatPay.setVisibility(View.GONE);
            }

            if (vipPriceInfoCheck.hasAliPay()) {

                if (payType == null) {
                    payType = SZConst.ALIPAY;
                    setPayTypeCheck();
                }
                rltAlipay.setVisibility(View.VISIBLE);
            } else {
                rltAlipay.setVisibility(View.GONE);
            }
            /**支付SKU备注信息，目前用于显示持续订阅说明*/
            if (SZValidatorUtil.isValidString(vipPriceInfoCheck.getNotes())) {
                txtVipSkuNotes.setText(vipPriceInfoCheck.getNotes());
                txtVipSkuNotes.setVisibility(View.VISIBLE);
            } else {
                txtVipSkuNotes.setVisibility(View.GONE);
            }
            lltContinuePay.setVisibility(vipPriceInfoCheck.isSubscription() ? View.VISIBLE : View.GONE);
        } else {
            rltAlipay.setVisibility(View.GONE);
            rltWechatPay.setVisibility(View.GONE);
            lltContinuePay.setVisibility(View.GONE);
            txtVipSkuNotes.setVisibility(View.GONE);
        }
    }

    public void setVipUserInfoView() {
        imgVip.setVisibility(View.VISIBLE);
        txtNormalUser.setVisibility(View.GONE);
        lltVipDate.setVisibility(View.VISIBLE);
        imgAvatar.setBorderWidth(SZUtil.dip2px(3));
        imgAvatar.invalidate();
        txtNickname.setTextColor(getResources().getColor(R.color.txtVipNicknameColor));
        txtVipDate.setText(SZDateUtil.getShowYearMonthDate(new Date(getVipUserInfo().getMemberValidityTime())));
    }

    public void setNormalUserView() {
        imgVip.setVisibility(View.GONE);
        txtNormalUser.setVisibility(View.VISIBLE);
        lltVipDate.setVisibility(View.GONE);
        imgAvatar.setBorderWidth(0);
        imgAvatar.invalidate();
        txtNickname.setTextColor(getResources().getColor(android.R.color.white));
    }

    @Override
    public boolean isShowTitleInit() {
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isPrepared() && !isLogin(false)) {
            if (isLogin(false)) {
                setUserInfoView();
                onReloadData(false);
            }
        }
    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.imgBackSub) {
            onBackPressed();
        } else if (viewId == R.id.btnPay) {
            if (isLogin(true)) {
                if (vipPriceInfoCheck == null) {
                    SZToast.warning("请先点击选择VIP套餐！");
                    return;
                }
                if (chkBoxAgree.isChecked()) {
                    pay();
                } else {
                    if (lltContinuePay.getVisibility() == View.VISIBLE) {
                        SZUtil.showAgreeTwoProtocolAlert(getActivity(), "同意并支付", getString(R.string.vip_service_agreement_symbol),
                                getVipProtocolUrl(), "《自动续费服务说明》", getVipContinueProtocolUrl(), getWebViewActivity(), new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        chkBoxAgree.setChecked(true);
                                        pay();
                                    }
                                });
                    } else {
                        SZUtil.showAgreeProtocolAlert(this, "同意并支付", getString(R.string.vip_service_agreement_symbol),
                                getVipProtocolUrl(), getWebViewActivity(),
                                new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        chkBoxAgree.setChecked(true);
                                        pay();
                                    }
                                });
                    }
                }
            }
        } else if (viewId == R.id.rltAlipay) {
            payType = SZConst.ALIPAY;
            setPayTypeCheck();
        } else if (viewId == R.id.rltWechatPay) {
            payType = SZConst.WXPAY;
            setPayTypeCheck();
        } else if (viewId == R.id.txtGetInvoice) {
            if (isLogin(true)) {
                startActivity(getInvoiceUrl(), getWebViewActivity());
            }
        } else if (viewId == R.id.txtVipProtocol) {
            startActivity(getVipProtocolUrl(), getWebViewActivity());
        } else if (viewId == R.id.txtVipContinueProtocol) {
            startActivity(getVipContinueProtocolUrl(), getWebViewActivity());
        } else if (viewId == R.id.imgVipService) {
            ShareWeChat.getInstance().openCompanyService(
                    "ww319db112ce746335", "https://work.weixin.qq.com/kfid/kfc539223cd934af350"
            );
        }
    }

    public String getInvoiceUrl() {
        return "https://www.xiangmaikeji.com/invoice.html?appToken=" + SZApp.getInstance().getUserToken()
                + "&applicationId=" + SZApp.getInstance().getSZAppId() + "#/OrderList";
    }

    public void requestVipUserInfo(Observable<String> observable) {
        request(observable, new SZCommonResponseListener() {
            @Override
            public void onResponseSuccess(String data) {
                List<VipInfo> vipInfoList = new Gson().fromJson(data, new TypeToken<List<VipInfo>>() {
                }.getType());
                if (SZValidatorUtil.isValidList(vipInfoList)) {
                    setVipUserInfo(vipInfoList.get(0));
                    UserManager.getInstance().setVipInfo(vipInfoList.get(0));
                    setVipUserInfoView();
                } else {
                    setVipUserInfo(null);
                    UserManager.getInstance().setVipInfo(null);
                    setNormalUserView();
                }
                getVipPrice();
            }

            @Override
            public void onResponseError(int errorCode, String errorMsg) {
                showErrorWithMsg(errorCode, errorMsg);
            }
        });
    }

    private void pay() {
        btnPay.setEnabled(false);
        showBar(true, false);
        String uuid = null;
        try {
            uuid = UUID.randomUUID().toString().replace("-", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        request(SZRetrofitManager.getInstance().getSZRequest().submitOrderV2(getUserId(), payType, uuid, vipPriceInfoCheck.getFpId(), getWeChatAppId()), new SZCommonResponseListener() {
            @Override
            public void onResponseSuccess(String data) {
                btnPay.setEnabled(true);
                new PayManager(getActivity(), SZConst.ALIPAY.equals(payType) ? PayType.ALIPAY : PayType.WECHAT, data, new PayManager.OnPayListener() {
                    @Override
                    public void onPaySuccess() {
                        closeBar();
                        startActivity(getSynchronizeVipClass());
                        finish();
                    }

                    @Override
                    public void onPayCancel() {
                        isCancelPay = true;
                        closeBar();
                        SZToast.warning("您取消了支付!");
                    }

                    @Override
                    public void onPayFailed() {
                        closeBar();
                        SZToast.error("支付失败,请重试!");
                    }
                }).toPay();
            }

            @Override
            public void onResponseError(int errorCode, String errorMsg) {
                btnPay.setEnabled(true);
                closeBar();
            }
        });
    }


    public abstract int getVipRecyclerViewSpanCount();

    public abstract List<VipPowerInfo> getVipPowerInfoList();

    public abstract Observable<String> getVipUserObservable();

    public abstract boolean isShowGetInvoice();

    public abstract void setVipUserInfo(VipInfo vipInfo);

    public abstract String getAvatar();

    public abstract String getNickname();

    public abstract VipInfo getVipUserInfo();

    public abstract String getUserId();

    public abstract String getWeChatAppId();

    public abstract String getVipProtocolUrl();

    public abstract String getVipContinueProtocolUrl();

    public abstract Class<?> getSynchronizeVipClass();

    public abstract Class<? extends SZBaseWebActivity> getWebViewActivity();

    public abstract Class<? extends SZPayVipNewActivity> getPayActivity();

    public abstract boolean isShowVipPowerDesc();

    /**
     * 挽留会员是否在支付后返回才显示
     * @return true 支付后，返回才显示，false 无论是否支付，返回时都显示
     */
    public abstract boolean isShowRetentionVipByCancelPay();

    /**
     * 返回true，代表不需要后续触发vip权限描述弹窗，反之则需要
     *
     * @param position
     * @param vipPowerInfo
     * @return
     */
    public boolean onVipPowerItemClick(int position, VipPowerInfo vipPowerInfo) {
        return true;
    }


    @Override
    public void onBackPressed() {
        if (!showRetentionVip()) {
            super.onBackPressed();
        }
    }
    private AlertWidget alertWidgetRetentionVip;

    public boolean showRetentionVip() {
        if(isShowRetentionVipByCancelPay()) {
            if (!isCancelPay) {
                return false;
            }
        }
        VipInfo vipInfo = getVipUserInfo();
        if (vipInfo != null && vipInfo.isVipValid()) {
            return false;
        }
        if (alertWidgetRetentionVip == null && SZValidatorUtil.isValidList(vipRetentionPriceInfoList)) {
            final VipPriceInfo vipPriceInfo = vipRetentionPriceInfoList.get(0);
            alertWidgetRetentionVip = new AlertWidget(this);
            alertWidgetRetentionVip.show(R.layout.alert_retention_vip);

            TextView txtName = alertWidgetRetentionVip.getWindow().findViewById(R.id.txtName);
            TextView txtDesc = alertWidgetRetentionVip.getWindow().findViewById(R.id.txtDesc);
            View viewDescLine = alertWidgetRetentionVip.getWindow().findViewById(R.id.viewDescLine);
            TextView txtPrice = alertWidgetRetentionVip.getWindow().findViewById(R.id.txtPrice);
            TextView txtResidueTime = alertWidgetRetentionVip.getWindow().findViewById(R.id.txtResidueTime);
            TextView txtDiscountDesc = alertWidgetRetentionVip.getWindow().findViewById(R.id.txtDiscountDesc);
            ImageView imgTag = alertWidgetRetentionVip.getWindow().findViewById(R.id.imgTag);
            TextView txtVipSkuNotes = alertWidgetRetentionVip.getWindow().findViewById(R.id.txtVipSkuNotes);
            TextView txtBuy = alertWidgetRetentionVip.getWindow().findViewById(R.id.txtBuy);
            TextView txtGiveUp = alertWidgetRetentionVip.getWindow().findViewById(R.id.txtGiveUp);
//            loadImg(imgTag, "https://cdn.image.xiangmaikeji.com/upload/20240911/43e684ceab32b87a02dbb7e4a7358f3e.png");
            txtName.setText(vipPriceInfo.getFpName());
            txtDesc.setText(vipPriceInfo.getFpSubject());
            txtPrice.setText(vipPriceInfo.getFpPrice());
            viewDescLine.setVisibility(vipPriceInfo.hasDeleteLine() ? View.VISIBLE : View.GONE);

            /**支付SKU备注信息，目前用于显示持续订阅说明*/
            if (SZValidatorUtil.isValidString(vipPriceInfo.getNotes())) {
                txtVipSkuNotes.setText(vipPriceInfo.getNotes());
                txtVipSkuNotes.setVisibility(View.VISIBLE);
            } else {
                txtVipSkuNotes.setVisibility(View.GONE);
            }

            if (SZValidatorUtil.isValidString(vipPriceInfo.getDiscountDesc())) {
                txtDiscountDesc.setVisibility(View.VISIBLE);
                txtDiscountDesc.setText(vipPriceInfo.getDiscountDesc());
            } else {
                txtDiscountDesc.setVisibility(View.GONE);
            }
            txtBuy.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isLogin(true)) {
                        alertWidgetRetentionVip.close();
                        startActivity(vipPriceInfo, getPayActivity());
                        SZManager.getInstance().onUMEvent(SZConst.EVENT_CLICK_RETENTION_VIP);
                    }
                }
            });
            txtGiveUp.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alertWidgetRetentionVip.close();
                    finish();
                }
            });
            SZManager.getInstance().onUMEvent(SZConst.EVENT_RETENTION_VIP_SHOW);
            return true;
        }
        return false;
    }
}

